package fortunata.servlets;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

import fortunata.fswapps.vpoet.Vpoet;

public class OmemoRequestServlet extends HttpServlet {


    /**
     * Initializes the servlet. It assigns the path to the onto files (defs and instances). Assumes that this servlet
     * is installed in the Fortunata web application
     * @param config
     * @throws javax.servlet.ServletException
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
    }
    /**
     * Default constructor. Creates a XML/RPC Client
     */
    public OmemoRequestServlet(){

         //Moved to init(...)
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
/*        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("GET Request. No Form Data Posted");*/
        doSomething(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse res)
            throws IOException, ServletException {
        doSomething(request, res);
    }

    public void doSomething(HttpServletRequest request, HttpServletResponse res)
            throws IOException, ServletException {

        PrintWriter out = res.getWriter();
        String actionParam = request.getParameter("action");
        // Handles ?action=getElemValue&ontoElem=foaf.Person.firstName&dataSource=http://www.ii.uam.es/~mrico/foaf.rdf

        if (actionParam.equals("getElemValue")){
           String valOntoElem    = request.getParameter("ontoElem");
           String valdataSource = request.getParameter("dataSource");
           getElemValue(valOntoElem, valdataSource, out);
        }
        // Handle ?action=renderShow&object=whateverURL&outformat=HTML
        //if (actionParam.equals("renderOutput")){

    }

    /**
     *  Reads the data source and looks for the element
     * @param ontoElem    Example: foaf.Person.firstName
     * @param dataSource  Example: http://www.ii.uam.es/~mrico/foaf.rdf
     * @param out
     * @return the value of the element (or null if the element is not found)
     */
    public void getElemValue(String ontoElem, String dataSource, PrintWriter out){
       out.println ("testing getElemValue");
    }

    /**
     * Query the model for a design given an ontoElem and a provider.
     * @param m
     * @param ontoElem
     * @param providerID
     * @return the URI of the design or null if there is no one available. If many are available, returns the first one. TODO
     */
    private String queryModel(OntModel m, String ontoElem, String providerID){
      Vpoet vpoet = new Vpoet();
      String queryString = "PREFIX vpoet: <" + vpoet.getURI() + "> \n" +
                           "SELECT ?x \n" +
                           "WHERE \n" +
                           " { ?x vpoet:ontoElemID " +  "\"" + ontoElem   +  "\" . \n" +
                           "   ?x vpoet:providerID " +  "\"" + providerID +  "\" . \n" +
                           " }";
      Query query = QueryFactory.create(queryString) ;
      QueryExecution qexec = QueryExecutionFactory.create(query, m) ;
      String res = null;
      try {
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; ){
          QuerySolution sol = results.nextSolution() ;
          res = sol.get("x").toString();
          break;  //Take the first one... TODO
        }
      } finally {
         qexec.close() ;
      }
      return res;
    }

    public static void main (String[]args){
      //  System.out.println(textBetween("tag", "{{{", "}}}",
      //           "Esto es lo que hay. tag \n {{{ <div>resultado ok<div>}}}"));
    }
}
